using System;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using BootstrapBlazor.Components;
using Identity.Interface;
using Identity.Models;
using Microsoft.Extensions.Options;
using WorkSystem.Data;
namespace WorkSystem.Services
{
    public class SystemNotificationService(
        IOptions<EmailConfig> emailConfig,
        IOptions<SmsConfig> smsConfig,
        IOptions<WeChatConfig> weChatConfig,
        IUser userService,
        IDispatchService<MessaggeBody> DispatchService
         ) : ISystemNotificationService
    {
        private readonly EmailConfig _emailConfig = emailConfig.Value;
        private readonly SmsConfig _smsConfig = smsConfig.Value;
        private readonly WeChatConfig _weChatConfig = weChatConfig.Value;
        private readonly IUser _userService = userService;

        private readonly IDispatchService<MessaggeBody> _DispatchService = DispatchService;

        /// <summary>   
        public async Task SendNotificationAsync(string NotificationType, DispatchType dispatchType, string title, string content, string userId)
        {
            // 获取用户通知偏好设置
            var user = _userService.GetUserByUserName(userId);
            if (user == null) return;
            
            switch (user.NotificationType)
            {
                case 通知方式.邮件:
                    await SendEmailNotificationAsync(user.Email, title, content);
                    break;
                case 通知方式.短信:
                    if (!string.IsNullOrEmpty(user.PhoneNumber))
                    {
                        await SendSMSNotificationAsync(user.PhoneNumber, content);
                    }
                    break;
                case 通知方式.企业微信:
                    if (!string.IsNullOrEmpty(user.WeChatId))
                    {
                        await SendWeChatNotificationAsync(user.WeChatId, content);
                    }
                    break;
            }
   

            // 总是发送系统通知
            await  SendSystemNotificationAsync(NotificationType, dispatchType,title , content, userId);
 
        }

        public async Task SendSMSNotificationAsync(string phoneNumber, string message)
        {
            try
            {
                // 实际项目中替换为真实的短信服务API调用
                // 这里以阿里云短信服务为例的伪代码
                /*
                var client = new AliyunClient(_smsConfig.ApiKey, _smsConfig.ApiSecret);
                var request = new SendSmsRequest {
                    PhoneNumbers = phoneNumber,
                    SignName = "您的签名",
                    TemplateCode = "SMS_123456",
                    TemplateParam = JsonConvert.SerializeObject(new { code = message })
                };
                var response = await client.ExecuteAsync(request);
                if (!response.IsSuccess) throw new Exception(response.Message);
                */

                // Console.WriteLine($"短信已发送到 {phoneNumber}: {message}");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                // Console.WriteLine($"发送短信失败: {ex.Message}");
                throw new NotificationException("短信发送失败", ex);
            }
        }

        public async Task SendEmailNotificationAsync(string email, string subject, string body)
        {
            try
            {
                using var smtpClient = new SmtpClient(_emailConfig.SmtpServer)
                {
                    Port = _emailConfig.Port,
                    Credentials = new NetworkCredential(_emailConfig.Username, _emailConfig.Password),
                    EnableSsl = true,
                };

                var mailMessage = new MailMessage
                {
                    From = new MailAddress(_emailConfig.FromAddress, _emailConfig.DisplayName),
                    Subject = subject,
                    Body = body,
                    IsBodyHtml = true,
                };
                mailMessage.To.Add(email);

                await smtpClient.SendMailAsync(mailMessage);
                // Console.WriteLine($"邮件已发送到 {email}: {subject}");
            }
            catch (Exception ex)
            {
                // Console.WriteLine($"发送邮件失败: {ex.Message}");
                throw new NotificationException("邮件发送失败", ex);
            }
        }

        public async Task SendWeChatNotificationAsync(string openId, string message)
        {
            try
            {
                // 实际项目中替换为微信服务号API调用
                /*
                var accessToken = await GetWeChatAccessTokenAsync();
                var client = new HttpClient();
                var url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={accessToken}";
                var request = new WeChatTemplateMessage {
                    touser = openId,
                    template_id = "您的模板ID",
                    data = new {
                        content = new { value = message, color = "#173177" }
                    }
                };
                var response = await client.PostAsJsonAsync(url, request);
                response.EnsureSuccessStatusCode();
                */

                // Console.WriteLine($"微信通知已发送到 {openId}: {message}");
                await Task.CompletedTask;
            }
            catch (Exception ex)
            {
                // Console.WriteLine($"发送微信通知失败: {ex.Message}");
                throw new NotificationException("微信通知发送失败", ex);
            }
        }

        public async Task SendSystemNotificationAsync(string NotificationType, DispatchType dispatchType, string title, string content, string userId)
        {
            try
            {
                _DispatchService.Dispatch(new DispatchEntry<MessaggeBody>()
                {
                    Name = NotificationType,
                    Entry = new MessaggeBody()
                    {
                        Title = title,
                        Content = content,
                        Type = dispatchType,
                        Username = userId,
                    }
                });
 
            }
            catch (Exception ex)
            {
                // Console.WriteLine($"保存系统通知失败: {ex.Message}");
                throw new NotificationException("系统通知保存失败", ex);
            }
        }

        private async Task<string> GetWeChatAccessTokenAsync()
        {
            // 获取微信AccessToken的伪代码
            /*
            var client = new HttpClient();
            var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={_weChatConfig.AppId}&secret={_weChatConfig.AppSecret}";
            var response = await client.GetAsync(url);
            var result = await response.Content.ReadFromJsonAsync<WeChatTokenResponse>();
            return result.AccessToken;
            */

            return "mock_access_token";
        }
    }

    public class NotificationException : Exception
    {
        public NotificationException(string message, Exception innerException)
            : base(message, innerException) { }
    }
}
